package com.weavernorth.updateKaoQin;

import com.api.formmode.page.util.Util;
import com.weavernorth.updateKaoQin.pojo.userGoOutPojo;
import com.weavernorth.util.Logger4jUtil;
import org.apache.log4j.Logger;
import weaver.common.DateUtil;
import weaver.conn.ConnectionPool;
import weaver.conn.RecordSet;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.wechat.util.Utils;

import java.sql.Connection;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.weavernorth.util.MyCommonUtils.getUseridByCode;
import static com.weavernorth.util.dateUtils.*;
import static com.weavernorth.util.dateUtils.isValidDate;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.updateKaoQin
 * @date: 2022/1/10 16:51
 * @description: 外出人员考勤按弹性时间处理：针对现有外出人员，
 * 如果上、下班在弹性时间节点内时，考勤报表显示考勤异常的情况进行处理，允许外出情况下也可以按照弹性考勤执行
 */
public class zGoOutKqFlush_Timmer extends BaseCronJob {
    private String gh;
    private String begindate;
    private String endate;

    public String getGh() {
        return gh;
    }

    public void setGh(String gh) {
        this.gh = gh;
    }

    public String getBegindate() {
        return begindate;
    }

    public void setBegindate(String begindate) {
        this.begindate = begindate;
    }

    public String getEndate() {
        return endate;
    }

    public void setEndate(String endate) {
        this.endate = endate;
    }

    public static ConnectionPool pool = ConnectionPool.getInstance();
    public Connection conn;
    public Statement statement;

    @Override
    public void execute() {
        Logger log = Logger4jUtil.getLoggerByName("/Timmer/zGoOutKqFlush_Timmer/");
        log.info("刷新外出人员考勤报表定时任务开始=====>");
        String strYesterday = DateUtil.getYesterday();
        String strBegin = "";
        String strEnd = "";
        String strGh = "";
        //获取当前日期
        String nowDate = getYearMonthDay();
        String year = nowDate.split("-")[0];
        String month = nowDate.split("-")[1];
        //获取当前日期天数
        String day = nowDate.split("-")[2];
        if (Integer.parseInt(day) > 4) {//当前日期在4号之后,取本月
            log.info("当前日期在4号之后时：");
            strBegin = year + "-" + month + "-01";
            log.info("开始日期：" + strBegin);
            strEnd = nowDate;
            log.info("结束日期：" + strEnd);
        } else {
            strBegin = getPreMonthFirstDate();//获取上个月第一天
            log.info("开始日期：" + strBegin);
            strEnd = nowDate;
            log.info("结束日期：" + strEnd);
        }
        if (begindate != null) {
            if (isValidDate(begindate, "yyyy-MM-dd")) {
                strBegin = begindate;
                log.info("日期参数-开始日期：" + strBegin);
            }

        }
        if (endate != null) {
            if (isValidDate(endate, "yyyy-MM-dd")) {
                strEnd = endate;
                log.info("日期参数-结束日期：" + strEnd);
            }
        }
        if (gh != null) {
            strGh = gh;
        }
        if ("".equals(strBegin)) {
            strBegin = strYesterday;
        }
        if ("".equals(strEnd)) {
            strEnd = strYesterday;
        }
        //两个日期比大小，开始日期大于结束日期时要进行交换
        String strTemp = "";
        if (strBegin.compareTo(strEnd) > 0) {
            strTemp = strBegin;
            strBegin = strEnd;
            strEnd = strTemp;
        }
        RecordSet rs = new RecordSet();

        String strQuery_flowid = "SELECT ID FROM workflow_base WHERE WORKFLOWNAME LIKE'%外出申请流程%'";
        rs.execute(strQuery_flowid);
        String str_workFlowids = "";
        while (rs.next()) {
            str_workFlowids += Utils.null2String(rs.getString("id")) + ",";

        }
        str_workFlowids = str_workFlowids.substring(0, str_workFlowids.length() - 1);
        log.info("外出workflowid：" + str_workFlowids);

        //region[1.获取外出申请记录]
        //只取安全级别大于13的人员(即排除店铺人员)
        String strSql = "SELECT  n.detail_resourceid userid,n.detail_fromdate begindate,n.detail_fromTime beginTime,n.detail_todate endate,n.detail_toTime endTime,m.requestid,b.currentnodetype,n.detail_duration hour  " +
                "FROM  FORMTABLE_MAIN_120 m,FORMTABLE_MAIN_120_dt1 n,workflow_requestbase b,HRMRESOURCE h WHERE " +
                "m.id=n.mainid and m.requestid=b.requestid AND n.detail_resourceid=h.id AND h.seclevel>13 and b.workflowid in( " + str_workFlowids + ")  AND b.currentnodetype = 3  AND to_date(n.detail_fromdate, 'yyyy-mm-dd') BETWEEN to_date('" + strBegin + "','yyyy-mm-dd')  AND to_date('" + strEnd + "','yyyy-mm-dd')" +
                " AND to_date(n.detail_todate, 'yyyy-mm-dd') BETWEEN to_date('" + strBegin + "','yyyy-mm-dd')  AND to_date('" + strEnd + "','yyyy-mm-dd') AND n.detail_duration !=1";
        if (!"".equals(strGh)) {
            String strUserid = getUseridByCode(strGh);
            strSql += " and n.detail_resourceid=" + strUserid;
        }
        log.info("执行外出申请人员考勤刷新的sql:" + strSql);
        rs.execute(strSql);
        //endregion
        try {
            conn = pool.getConnection();
            statement = conn.createStatement();
            String update_main = "";
            String update_detail = "";
            while (rs.next()) {
                String strUserid = Utils.null2String(rs.getString("userid"));
                log.info("人员id:" + strUserid);
                String strRequest = Utils.null2String(rs.getString("requestid"));
                log.info("requestId:" + strRequest);
                String begindate = Utils.null2String(rs.getString("begindate"));
                log.info("开始日期:" + begindate);
                String beginTime = Utils.null2String(rs.getString("beginTime"));
                log.info("开始时间:" + beginTime);
                String endate = Utils.null2String(rs.getString("endate"));
                log.info("结束日期:" + endate);
                String endTime = Utils.null2String(rs.getString("endTime"));
                log.info("结束时间:" + endTime);
                String hours = Utils.null2String(rs.getString("hour"));
                log.info("外出小时数:" + hours);
                Date start_flag = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(begindate+" 10:00");
                Date start_date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(begindate+" "+beginTime);
                Date end_flag = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(endate+" 17:00");
                Date end_date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(endate+" "+endTime);
                boolean isDouble = Util.isDouble(hours);
                if(isDouble){
                    //外出申请开始时间在10点之前,更新异常考勤为正常
                    if (start_date.compareTo(start_flag)<1) {
                        //外出开始时间为上午时，更新考勤主表
                        update_main="UPDATE KQ_FORMAT_TOTAL SET belate=0,belatemins=0,attendancedays=1,attendancemins=workdays WHERE resourceid="+strUserid+" AND kqdate='"+begindate+"' and attendancemins<workmins";
                        log.info("外出开始时间在10点前-更新语句：" + update_main);
                        statement.addBatch(update_main);
                        //外出开始时间为上午时，更新考勤明细表
                        update_detail="UPDATE KQ_FORMAT_detail SET attendanceMins=480,belatemins=0 WHERE resourceid='"+strUserid+"' AND kqdate='"+begindate+"'";
                        log.info("外出开始时间在10点前-更新语句：" + update_detail);
                        statement.addBatch(update_detail);
                    }
                    //外出申请结束时间在17点之后，更新异常考勤为正常
                    if (end_date.compareTo(end_flag)>-1) {
                        //外出结束时间为下午时，更新考勤主表
                        update_main="UPDATE KQ_FORMAT_TOTAL SET belate=0,belatemins=0,attendancedays=1,attendancemins=workdays WHERE resourceid="+strUserid+" AND kqdate='"+endate+"' and attendancemins<workmins";
                        log.info("外出结束时间在17点后-语句：" + update_main);
                        statement.addBatch(update_main);
                        //外出开始时间为下午时，更新考勤明细表
                        update_detail="UPDATE KQ_FORMAT_detail SET attendanceMins=480,belatemins=0 WHERE resourceid='"+strUserid+"' AND kqdate='"+endate+"'";
                        log.info("外出开始时间在10点前-更新语句：" + update_detail);
                        statement.addBatch(update_detail);
                    }

                }

            }

            Long begin1 = System.currentTimeMillis();
            statement.executeBatch();
            Long end1 = System.currentTimeMillis();
            log.info("批量更新耗时：" + (end1 - begin1) + "(毫秒)");
            conn.close();
            statement.close();

        } catch (Exception ex) {
            log.info("更新考勤异常，异常信息："+ex.toString());
        }
//        List<userGoOutPojo> newList=new ArrayList<userGoOutPojo>();
//        //根据人员id,开始日期,结束日期分组统计外出小时数,并放入新的集合中
//        userGoOutPojoList.stream().collect(Collectors
//                .groupingBy(user -> new userGoOutPojo(user.getUserid(),user.getBeginDate(),user.getEndDate()),
//                        Collectors.summarizingDouble(userGoOutPojo::getHours)))
//                .forEach((k,v) ->{k.setHours(v.getSum());newList.add(k);});
        log.info("定时任务结束=====>");


    }

}
